# Copyright (c) 2009 Vitja Makarov <vitja.makarov@gmail.com>
# Licensed under the terms of the MIT License (see LICENSE.txt)

from django import forms
from django.forms.forms import BoundField
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from django.db import models

from translate.trans import *
from translate.models import Language, SimpleTranslation

class OriginalField(forms.CharField):
    def widget_attrs(self, widget):
        return {'readonly': 'true'}

def get_original_field(field_name):
    return 'original_%s' % field_name

def get_translation_field(field_name):
    return 'translation_%s' % field_name

class ModelTranslateForm(forms.Form):
    def __init__(self, object, *args, **kwargs):
        self.lang = kwargs.pop('lang', None)
        if self.lang is None:
            from django.utils.translation import get_language
            self.lang = get_language()
        super(ModelTranslateForm, self).__init__(*args, **kwargs)

        self.object = object
        if object.Translate.model:
            self.translate_model = object.get_translate_model(self.lang)
        else:
            self.translate_model = None

        self.initial = {}
        self._fields_group = []

        for field_name in object.Translate.fields:
            field = object._meta.get_field_by_name(field_name)[0]
            value = getattr(object, field_name)

            if isinstance(field, models.TextField):
                widget = forms.widgets.Textarea
            else:
                widget = None

            original_field = OriginalField(required=False, widget=widget)
            translation_field = forms.CharField(widget=widget, required=False)

            self.fields[get_original_field(field_name)] = original_field
            self.fields[get_translation_field(field_name)] = translation_field

            self.initial[get_original_field(field_name)] = value
            if self.translate_model:
                self.initial[get_translation_field(field_name)] = self.translate_model.get_value(field_name)
            else:
                try:
                    self.initial[get_translation_field(field_name)] = translator.get_translation(value, lang=self.lang)
                except KeyError:
                    self.initial[get_translation_field(field_name)] = None
            self._fields_group.append((field, original_field, translation_field))

    @property
    def fields_group(self):
        for field, orig, trans in self._fields_group:
            yield {'name': field.verbose_name,
                   'original': BoundField(self, orig, get_original_field(field.name)),
                   'translation': BoundField(self, trans, get_translation_field(field.name))
                   }

    def save(self):
        if self.translate_model:
            for field_name in self.object.Translate.fields:
                self.translate_model.set_value(field_name, self.cleaned_data[get_translation_field(field_name)])
            self.translate_model.save()
        else:
            language = Language.objects.get(code=self.lang)
            for field_name in self.object.Translate.fields:
                original = self.cleaned_data[get_original_field(field_name)]
                translated = self.cleaned_data[get_translation_field(field_name)]
                if translated != self.initial[get_translation_field(field_name)]:
                    try:
                        trans = translator.get_translation(original, lang=self.lang)
                    except KeyError:
                        trans = SimpleTranslation()
                        trans.original = original
                        trans.lang = language
                    trans.translation = translated
                    trans.save()
